﻿namespace EyeOpen.Validation
{
    /// <summary>
    /// Validates a string length.
    /// </summary>
    public class MinimumLengthValidator : Validator<string>
    {
        private ValidationStatus validationStatus;

        /// <summary>
        /// Initializes a new instance of the <see cref="MinimumLengthValidator"/> class.
        /// </summary>
        /// <param name="maximumLength">The minimum length.</param>
        public MinimumLengthValidator(int minimumLength)
        {
            MinimumLength = minimumLength;
        }

        private enum ValidationStatus
        {
            StringNull,
            Length,
            Valid
        }

        /// <summary>
        /// Gets or sets the minimum length.
        /// </summary>
        /// <value>The length.</value>
        public int MinimumLength
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the validation message.
        /// </summary>
        /// <value>The validation message.</value>
        public override string ValidationMessage
        {
            get 
            {
                CheckValidationIsCalled();

                if (validationStatus == ValidationStatus.Valid) 
                {
                    return null;
                }

                if (validationStatus == ValidationStatus.StringNull) 
                {
                    return "Value cannot be string empty or null.";
                }

                const string Message = "String length cannot be less than {0}.";
                return string.Format(Message, MinimumLength);
            }
        }

        /// <summary>
        /// Determines whether the specified string is at least the specified length.
        /// </summary>
        /// <param name="obj">The string value.</param>
        /// <returns>
        /// <c>true</c> if the specified string is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(string obj)
        {
            ValidationCalled();

            if (string.IsNullOrEmpty(obj))
            {
                validationStatus = ValidationStatus.StringNull;
                return false;
            }

            var valid = obj.Length >= MinimumLength;
            
            if (!valid)
            {
                validationStatus = ValidationStatus.Length;
            }
            else
            {
                validationStatus = ValidationStatus.Valid;
            }

            return valid;
        }
    }
}